<template>
  <div class="trade-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>交易管理</h2>
          <div class="header-buttons">
          
            <el-button type="primary" @click="$router.push('/trade-management/create')">创建交易</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" class="search-form">
          <el-form-item label="组合名称">
            <el-select v-model="searchForm.portfolio" placeholder="选择组合" clearable>
              <el-option
                v-for="portfolio in portfolios"
                :key="portfolio.id"
                :label="portfolio.name"
                :value="portfolio.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交易类型">
            <el-select v-model="searchForm.action" placeholder="选择类型" clearable>
              <el-option label="买入" value="买入"></el-option>
              <el-option label="卖出" value="卖出"></el-option>
              <el-option label="调仓" value="调仓"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交易日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="已完成" value="已完成"></el-option>
              <el-option label="处理中" value="处理中"></el-option>
              <el-option label="已取消" value="已取消"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 交易表格 -->
      <el-table :data="filteredTrades" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="portfolio" label="组合名称" width="150"></el-table-column>
        <el-table-column prop="action" label="交易类型" width="100">
          <template #default="scope">
            <el-tag :type="getActionType(scope.row.action)" v-if="scope.row.action">{{ scope.row.action }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fund" label="基金名称" width="150"></el-table-column>
        <el-table-column label="交易金额" width="120">
          <template #default="scope">
            {{ scope.row.amount ? formatMoney(scope.row.amount) : '暂无数据' }}
          </template>
        </el-table-column>
        <el-table-column label="交易份额" width="120">
          <template #default="scope">
            {{ scope.row.amount && scope.row.price ? calculateShares(scope.row) : '暂无数据' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="交易净值" width="120"></el-table-column>
        <el-table-column prop="date" label="交易日期" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" v-if="scope.row.status">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewTradeDetail(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="editTrade(scope.row)"
              :disabled="!scope.row.status || scope.row.status !== '处理中'">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="cancelTrade(scope.$index)"
              :disabled="!scope.row.status || scope.row.status !== '处理中'">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="totalTrades"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="交易详情"
      width="600px">
      <div v-if="currentTrade">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="组合名称">{{ currentTrade.portfolio }}</el-descriptions-item>
          <el-descriptions-item label="交易类型">
            <el-tag :type="getActionType(currentTrade.action)" v-if="currentTrade.action">{{ currentTrade.action }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="基金名称">{{ currentTrade.fund }}</el-descriptions-item>
          <el-descriptions-item label="交易金额">{{ currentTrade.amount ? formatMoney(currentTrade.amount) : '暂无数据' }}</el-descriptions-item>
          <el-descriptions-item label="交易份额">{{ currentTrade.amount && currentTrade.price ? calculateShares(currentTrade) : '暂无数据' }}</el-descriptions-item>
          <el-descriptions-item label="交易净值">{{ currentTrade.price }}</el-descriptions-item>
          <el-descriptions-item label="交易日期">{{ currentTrade.date }}</el-descriptions-item>
          <el-descriptions-item label="交易状态">
            <el-tag :type="getStatusType(currentTrade.status)" v-if="currentTrade.status">{{ currentTrade.status }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentTrade.status === '已完成'" class="trade-result" style="margin-top: 20px;">
          <h3>交易结果</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="实际成交份额">{{ currentTrade.amount && currentTrade.price ? calculateShares(currentTrade) : '暂无数据' }}</el-descriptions-item>
            <el-descriptions-item label="手续费">{{ currentTrade.amount ? formatMoney(calculateFee(currentTrade)) : '暂无数据' }}</el-descriptions-item>
            <el-descriptions-item label="实际金额">{{ currentTrade.amount ? formatMoney(currentTrade.amount - calculateFee(currentTrade)) : '暂无数据' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TradeManagement',
  setup() {
    const store = useStore()
    const router = useRouter()
    const detailDialogVisible = ref(false)
    const currentTrade = ref(null)
    
    // 分页相关
    const pageSize = ref(10)
    const currentPage = ref(1)
    
    // 搜索表单
    const searchForm = reactive({
      portfolio: '',
      action: '',
      dateRange: [],
      status: ''
    })
    
    // 计算属性：获取组合列表
    const portfolios = computed(() => {
      return store.getters.getPortfolios
    })
    
    // 计算属性：获取过滤后的交易列表
    const filteredTrades = computed(() => {
      return store.getters.getTrades.filter(trade => {
        // 组合过滤
        const portfolioMatch = !searchForm.portfolio || trade.portfolio === searchForm.portfolio
        
        // 类型过滤
        const actionMatch = !searchForm.action || trade.action === searchForm.action
        
        // 状态过滤
        const statusMatch = !searchForm.status || trade.status === searchForm.status
        
        // 日期过滤
        let dateMatch = true
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          const startDate = searchForm.dateRange[0]
          const endDate = searchForm.dateRange[1]
          const tradeDate = trade.date
          dateMatch = tradeDate >= startDate && tradeDate <= endDate
        }
        
        return portfolioMatch && actionMatch && statusMatch && dateMatch
      }).slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
    })
    
    // 计算属性：获取总交易数
    const totalTrades = computed(() => {
      return store.getters.getTrades.length
    })
    
    // 生命周期钩子
    onMounted(() => {
      store.dispatch('loadTrades')
      store.dispatch('loadPortfolios')
    })
    
    // 方法：获取交易类型对应的标签类型
    const getActionType = (action) => {
      if (!action) return 'info'
      
      switch (action) {
        case '买入': return 'success'
        case '卖出': return 'danger'
        case '调仓': return 'warning'
        default: return 'info'
      }
    }
    
    // 方法：获取状态对应的标签类型
    const getStatusType = (status) => {
      if (!status) return 'info'
      
      switch (status) {
        case '已完成': return 'success'
        case '处理中': return 'warning'
        case '已取消': return 'info'
        default: return 'info'
      }
    }
    
    // 方法：格式化金额
    const formatMoney = (amount) => {
      if (amount === undefined || amount === null) return '¥ 0.00'
      
      return '¥ ' + amount.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    // 方法：计算交易份额
    const calculateShares = (trade) => {
      if (!trade || !trade.amount || !trade.price || trade.price === 0) {
        return '0.00 份'
      }
      
      const shares = trade.amount / trade.price
      return shares.toFixed(2) + ' 份'
    }
    
    // 方法：计算手续费
    const calculateFee = (trade) => {
      if (!trade || !trade.amount || !trade.action) {
        return 0
      }
      
      // 简单计算，买入费率0.15%，卖出费率0.5%，调仓费率0.3%
      const feeRate = {
        '买入': 0.0015,
        '卖出': 0.005,
        '调仓': 0.003
      }
      return trade.amount * (feeRate[trade.action] || 0)
    }
    
    // 方法：搜索交易
    const handleSearch = () => {
      currentPage.value = 1 // 重置到第一页
    }
    
    // 方法：重置搜索
    const resetSearch = () => {
      searchForm.portfolio = ''
      searchForm.action = ''
      searchForm.dateRange = []
      searchForm.status = ''
      currentPage.value = 1 // 重置到第一页
    }
    
    // 方法：查看交易详情
    const viewTradeDetail = (trade) => {
      currentTrade.value = trade
      detailDialogVisible.value = true
    }
    
    // 方法：编辑交易
    const editTrade = (trade) => {
      router.push({
        path: '/trade-management/create',
        query: { id: trade.id, mode: 'edit' }
      })
    }
    
    // 方法：取消交易
    const cancelTrade = (index) => {
      const trade = filteredTrades.value[index];
      if (!trade) return;
      
      ElMessageBox.confirm('确定要取消该交易吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('updateTradeStatus', { id: trade.id, status: '已取消' }).then(() => {
          ElMessage.success('交易已取消');
        }).catch(error => {
          ElMessage.error('取消交易失败: ' + error.message);
        });
      }).catch(() => {
        // 用户取消操作
      })
    }
    
    // 方法：处理页面大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1 // 重置到第一页
    }
    
    // 方法：处理页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    return {
      searchForm,
      detailDialogVisible,
      currentTrade,
      pageSize,
      currentPage,
      portfolios,
      filteredTrades,
      totalTrades,
      getActionType,
      getStatusType,
      formatMoney,
      calculateShares,
      calculateFee,
      handleSearch,
      resetSearch,
      viewTradeDetail,
      editTrade,
      cancelTrade,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.trade-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style> 